package com.web.core.base.service;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.blue.core.tree.TreeBuilder;
import com.blue.jdbc.JdbcDataSource;
import com.web.core.base.dao.AreaDao;
import com.web.core.base.model.Area;
import com.web.core.util.Const;
import com.web.core.util.WebException;

@Service
@Transactional
@JdbcDataSource(Const.DS_BASE)
public class AreaService
{
	@Resource
	private AreaDao areaDao;
	
	public AreaService()
	{
	}
	
	public void save(Area area)
	{
		if (area.getCode() != null && !area.getCode().isEmpty() && areaDao.exist(area, "code"))
			throw new WebException("代码已经存在：" + area.getCode());
		
		if (area.getParentId() != null && !areaDao.existParent(area.getParentId()))
			throw new WebException("上级ID不存在：" + area.getParentId());
		
		if (area.getId() == null)
		{
			areaDao.save(area);
		}
		else
		{
			areaDao.update(area);
		}
	}
	
	public Area get(Integer id)
	{
		Area area = areaDao.get(id);
		return area;
	}
	
	public Map<String, List<Area>> listTree(Area area)
	{
		List<Area> areaList = areaDao.list(area);
		return TreeBuilder.buildMenu(areaList);
	}
	
	public List<Area> list(Area area)
	{
		List<Area> areaList = areaDao.list(area);
		return areaList;
	}
	
}
